<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Request;
use think\Loader;
use think\Cache;


function ApiJson($code = 0, $msg = '', $data = [], $pageInfo = ['CurrPage' => 0, 'TotalPage' => 0, 'TotalItem' => 0, 'PageSize' => 0], $ret = 200)
{
    return [
        'ret' => $ret,
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
        'pageInfo' => $pageInfo
    ];
}
 function resJson($code=0,$msg="",$res=[],$pageInfo=[]){
     $Cstatic = controller('base/Cstatic');
     $token = md5(substr(time(),5,9));

    if($Cstatic->has("sid")){
        $sid = $Cstatic->get("sid");
        $rows = Cache::get($sid);
        if(is_array($rows)){
            $rows['token'] = $token;
            Cache::set($sid,$rows,3600*24);
        }
    }

    if(is_object($res)){
        if(is_callable(array($res , 'toArray'))){
            $res = array_merge($res->toArray(),['token'=>$token]);
        }else{
            $res = array_merge($res->getData(),['token'=>$token]);
        }

    }else{
        $res = array_merge($res,['token'=>$token]);
    }


     $page = getPage();
    $pageInfo_init = ['CurrPage' =>$page, 'TotalPage' => 0, 'TotalItem' => 0, 'PageSize' => 0];
    if(is_array($pageInfo)){

        $pageInfo  = array_merge($pageInfo_init,$pageInfo);
    }

     if(isset($res['pageInfo'])){
         $pageInfo  = array_merge($pageInfo_init,$res['pageInfo']);
         unset($res['pageInfo']);
     }

    return json(apiJson($code,$msg,$res,$pageInfo));
}

function failJson($msg="",$res=[],$pageInfo=[]){
    return resJson(0,$msg,$res,$pageInfo);
}

function sucessJson($msg="",$res=[],$pageInfo=[]){
    return resJson(1,$msg,$res,$pageInfo);
}


 function getPage(){
     $page = 0;
     $instance = Request::instance();
     $page_b = $instance->param("page");
     if(isset($page_b)){
         $page = $page_b;
     }
     return $page;
 }


 //获取群主key的配置信息
function get_m_config($key){
    $Configs = controller('base/Configs', 'event');
    $mouth_config = $Configs->get_ckkey($key);
    return $mouth_config;
}

//获取单独key的配置信息
function getOneConfigByKey($key){
    $model = new \app\base\model\Configs;
    return $model->getConfigByKey($key);
}


function getOneConfigById($id){
    $model = new \app\base\model\Configs;
    return $model->get_config_id($id);
}
function get_one_key($arr,$key){
    foreach($arr as $k=>$v){
        if($v['key']==$key){
            return $v['id'];
        }
    }
    return 0;
}

function get_one_value($arr,$id){
    foreach($arr as $k=>$v){
        if($v['id']==$id){
            return $v['value'];
        }
    }
    return 0;
}

function sort_by_name($x,$y){
    return $x['key']>$y['key'];
}


/**
 * @param $data 写入的data格式
 * @return false|int
 */
 function admin_logs($data){
     //admin_logs(["admin_user_id"=>0,"name"=>$name,"content"=>"第三方充值:{$name} 充值成功,单号：{$data['pay_no']}"]);
     $model = new \app\admin\model\SysMessage;
     $tdata = [
         "name"=>isset($data['name'])?$data['name']:"暂无模块",
         "action_man"=>$data['admin_user_id'],
         "code"=>1,
         "msg"=>$data['content'],
         "action"=>isset($data['action'])?$data['action']:"",
         "action_ip"=>Request::instance()->ip(),
         "content"=>isset($data['scan_nameData'])?json_encode($data['scan_nameData']):"暂无请求数据",
     ];

     return $model->save($tdata);
 }


 //获取股价行情 单个
 function gethq($stock,$base="sh"){
     $curl = new \http\Http();
     $res = $curl->get("http://hq.sinajs.cn/list=".$base.$stock);
     return handleHq($res);
 }

 function gethqone($stock,$base="sh"){
     $curl = new \http\Http();
     $res = $curl->get("http://hq.sinajs.cn/list=".$base.$stock);
     $res = mb_convert_encoding($res, "UTF-8", "GBK");
     return handleHqall($res);
 }
 //获取股价行情 多个
function gethqMony($stockArr,$base="sh"){
    $n_w = [];
     if(!is_array($stockArr)){
            return 0;
     }
    $stockArr = array_map(function($val) use($base){
                return $base.$val;
    },$stockArr);
    $stock_string = implode(",",$stockArr);

    $curl = new \http\Http();
    $res = $curl->get("http://hq.sinajs.cn/list=".$stock_string);

    preg_match_all("/\"(.*)\"/",$res,$arr);

    if(is_array($arr)){
            foreach($arr as $k=>$v){
                if(isset($v[0])){
                    $n_w[$stockArr[$k]]=$v[0];
                }

            }
    }

    if(is_array($n_w)&!empty($n_w)){
                foreach($n_w as $kk=>&$vv){
                    $vv = handleHq($vv);
                }
    }
    if(!empty($n_w)){
              $kw = [];
            foreach($n_w as $k=>$v){
                $o = strpos($k,$base);
                if(is_bool($o)&&$o==false){ //
                        $kw[$k] = $v;
                }else{
                    $k = str_replace($base,"",$k);
                    $kw[$k] = $v;
                }
            }
            $n_w = $kw;
    }

    return $n_w;

}

function handleHq($res){
    preg_match("/\"(.*)\"/",$res,$arr);
    if(!empty($arr)&&is_array($arr)&&isset($arr[1])){
        $arr_ = $arr[1];
        $row =  explode(',',$arr_);
        if(isset($row[3])){
            return $row[3];
        }
        return 0;
    }
    return 0;
}

function handleHqall($res){
    preg_match("/\"(.*)\"/",$res,$arr);
    if(!empty($arr)&&is_array($arr)&&isset($arr[1])){
        $arr_ = $arr[1];
        $row =  explode(',',$arr_);
        if(isset($row[3])){
            return $row;
        }
        return [];
    }
    return [];
}

 //发送验证码
 function sedMess($phone,$code){
     $status =['status'=>0,"msg"=>"异常"];
     $smsConfig = getConfigsms();//短信配置
    if(empty($smsConfig)){
        $status['msg'] = "系统暂无配置短信";
        return $status;
    }
     $cur_key = $smsConfig['key'];
     $m=ucfirst($cur_key);
     $classModel = '\\'."sms".'\\'.$m;
     if(class_exists($classModel)){
         $dxBao  = new $classModel;
         $dxBao->sedMess($phone,$code);
         $status['status'] = 1;
         $status['msg'] = "发送成功";
         return $status;
     }

    if($smsConfig['key']=="smsdisable"){
        $status['msg'] = "系统暂无配置短信";
        return $status;
    }


 }

function sedMessageAll($phone,$key,$code){


    $status =['status'=>0,"msg"=>"异常"];
    $smsConfig = getConfigsms();//短信配置
    if(empty($smsConfig)){
        $status['msg'] = "系统暂无配置短信";
        return $status;
    }

    if($smsConfig['key']=="smsdisable"){
        $status['msg'] = "系统暂无配置短信";
        return $status;
    }

    $cur_key = $smsConfig['key'];
    $m=ucfirst($cur_key);
    $classModel = '\\'."sms".'\\'.$m;
    if(class_exists($classModel)){
        $dxBao  = new $classModel;
        $dxBao->sedMessageAll($phone,$key,$code);
        $status['status'] = 1;
        $status['msg'] = "发送成功";
        return $status;
    }






}






 //获取vaule
 function getvs($value)
{
    $mouth_config = get_m_config("q_time");
    if(!empty($mouth_config)){
        $ids = array_column($mouth_config,"id");
        foreach($ids as $k=>$v){
            if($v==$value){
                return $mouth_config[$k]['value'];
            }
        }
    }
    return $value;
}


//获取消息个数
function getMessageNums($sid){
    $UsersMessage = new \app\out\model\UsersMessage;
    $rows = Cache::get($sid);
    $user_id = $rows['id'];
    return $UsersMessage->where(["user_id"=>$user_id,"status"=>0])->count();

}


//增加回执消息
function addMessage($user_id,$message){
    $UsersMessage = new \app\out\model\UsersMessage;
    $data = [
            "user_id"=>$user_id,
            "content"=>$message
    ];
    return $UsersMessage->save($data);

}


//用户资产计算
function  getMoney($sid){
    $rows = Cache::get($sid);
    $user_id = $rows['id'];
    $UsersMoney= new \app\np\model\UsersMoney; //用户资产
    $OrderDetails= new \app\np\model\OrderDetails;//订单详情
    $gpmoney = 0;
    //获取正在持仓的股票
    $rows_ = $OrderDetails->alias("a")
             ->field("a.Initial_price,a.equity_nums,shares.code")
             ->join("shares","shares.id=a.stock_id","left")
             ->where("a.user_id",$user_id)->where("a.status",2)->select();
    if(!empty($data)){
        foreach($data  as $k=>$v){
          $codemoney = gethq($v['code']);
             $gpmoney += $codemoney*$v['equity_nums'];
        }
    }
    $users =   $UsersMoney->field("advisable,stock_value,freeze,money,advisable,balance")->where("user_id",$user_id)->find();
    if($users){
        $users['gpmoney'] =$gpmoney;//股票总资产
        $users['all'] =$users['balance'] + $gpmoney;//股票总资产

        return $users;
    }
    return [];
}


//数组转XML
function arrayToXml($arr,$base="Response")
{
    $xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
    $xml .= "<{$base}>";
    foreach ($arr as $key=>$val)
    {
        if (is_numeric($val)){
            $xml.="<".$key.">".$val."</".$key.">";
        }else{
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
    }
    $xml.="</{$base}>";
    return $xml;
}



//数组转XML
function array2xml($arr, $level = 1) {
    $s = $level == 1 ?  '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' : '';
    foreach ($arr as $tagname => $value) {
        if (is_numeric($tagname)) {

            $tagname = $value['TagName'];

            unset($value['TagName']);

        }

        if (!is_array($value)) {

            $s .= "<{$tagname}>" . (!is_numeric($value) ? '<![CDATA[' : '') . $value . (!is_numeric($value) ? ']]>' : '') . "</{$tagname}>";

        } else {

            $s .= "<{$tagname}>" . array2xml($value, $level + 1) . "</{$tagname}>";

        }

    }
    $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);

    return $level == 1 ? $s . "" : $s;
}


//将XML转为array
function xmlToArray($xml)
{
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $values;
}





function ordersn(){
    $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
    $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5)  . sprintf('%02d', rand(0, 99));
    return $orderSn;
}


//用户绑卡 //四要素
function tieCard($AccountNo,$CertName,$CertNo,$Phone){
    $tdata = ['status'=>0,'msg'=>"异常","data"=>[]];
    $result =getConfigByZhifu();

    if($result['id']==38){
        //本元支付
        $pay = new \pay\Benyuan();
        $result =  $pay->tieCard($AccountNo,$CertName,$CertNo,$Phone);


        if(isset($result['Body'])){
            if($result['Body']['ResCode']!="0000"){

                $tdata   =  array_merge($tdata,['msg'=>$result['Body']['ResDes']]);
                return $tdata;
            }
            return array_merge($tdata,['status'=>1]);
        }

    }else if($result['id']==46)
    {//易通金服
        return array_merge($tdata,["status"=>2,'msg'=>"暂不支持第三方绑银行卡_易通金服"]);

    }
    return array_merge($tdata,["status"=>2,'msg'=>"暂不支持第三方绑银行卡"]);
}

function byThrityPayPC($deposit,$payNo,$CertName,$CertNo,$Phone,$bank_id=0){

    $tdata = ['status'=>0,'msg'=>"异常","data"=>[]];
    $result =getConfigByZhifu();

    if(empty($result)){
        return $tdata;
    }


    if($result['id']==59){

        $pay = new \pay\Znan();
        if(empty($bank_id)){
            return $tdata;
        }
        $getWay =  $pay->pcPay($deposit,$payNo,$bank_id);

        if(getOS()=="Linux"){
            error_log(json_encode($getWay).PHP_EOL, 3, "/home/wwwlogs/pc_znan.log");
        }else{
                file_put_contents("pc_znan.log",json_encode($getWay).PHP_EOL);
        }

        if(!$getWay){
            return array_merge($tdata,['msg'=>"第三方接口异常"]);
        }else{
            if(is_array($getWay)){
                return array_merge($tdata,['status'=>0,"msg"=>$getWay['msg']]);
            }
            return array_merge($tdata,['status'=>1],["data"=>["url"=>$getWay,"status"=>1]]);
        }
        return $tdata;
    }

    if($result['id']==58){

        $pay = new \pay\Tlian();
        if(empty($bank_id)){
            return $tdata;
        }
        $getWay =  $pay->pcPay($deposit,$payNo,$bank_id);
        if(!$getWay){
            return array_merge($tdata,['msg'=>"第三方接口异常"]);
        }else{
            if(is_array($getWay)){
                return array_merge($tdata,['status'=>0,"msg"=>$getWay['msg']]);
            }
            return array_merge($tdata,['status'=>1],["data"=>["url"=>$getWay,"status"=>1]]);
        }
        return $tdata;
    }
    return $tdata;
}

function filterPrivilege($res,$id){

    $arr = [];
    /**
     * 第一层处理
     */
    foreach($res as $k=>$v){
        if($v['parent_id']==$id) {
            $arr[] =    $v;
        }
    }

    return $arr;
}


function getZero($num){
    return  sprintf("%04d",$num);
}
function getZero5($num){
    return  sprintf("%05d",$num);
}

/**
 * @param $parms $parms =  array("601688.SH", "1M", 1, 1000000,"2018-02-13");
 * @return int
 */
function baojia($parms){
    ini_set('soap.wsdl_cache_enabled', "0"); //关闭wsdl缓存
    $soap = new SoapClient('http://180.167.11.114:8088/OtcOptionPricing.asmx?wsdl');
    $result =  $soap->__soapCall('Login',
        array(array(  'userId' => 'yingkang',
            'password' => '123456'))
    );
    $SESSION = $result->LoginResult;
    // $parms =  array("601688.SH", "1M", 1, 1000000,"2018-02-13");
    $getVal =  $soap->__soapCall('GetValue',
        array(array(
            'sessionID' => $SESSION,
            'dllName' => 'MuxinOtcPricingSystem',
            'funcName' => 'Core.GetOtcOptionPrice_Call',
            'inputs' => $parms,
        )));
    if(isset($getVal->GetValueResult)){
      $GetValueResult =   $getVal->GetValueResult ;
        $GetValueResult = str_replace("%","",$GetValueResult);
        return $GetValueResult;
    }else{
        return 0;
    }
}





function filterData($data,$staffData){

    return  array_filter($data,function($val,$key)use($staffData){
        return in_array($key,$staffData)&&!is_null($val);},ARRAY_FILTER_USE_BOTH);
}
function byThrityPay($deposit,$payNo,$CertName,$CertNo,$Phone,$user_id){

    if(getOS()=="Linux"){
        $files = "/home/wwwlogs/controller_zhifu.log";
        error_log(json_encode([$deposit,$payNo,$CertName,$CertNo,$Phone,$user_id]).PHP_EOL,3,$files);
    }
            $tdata = ['status'=>0,'msg'=>"异常","data"=>[]];
           $result =getConfigByZhifu();

           if(empty($result)){
               return $tdata;
           }




            if($result['id']==38){
            //本元支付
                $pay = new \pay\Benyuan();
                  $result =  $pay->byPay($deposit,$payNo,$CertName,$CertNo,$Phone);
                return array_merge($tdata,['status'=>1],["data"=>["url"=>$result],"status"=>1]);
            }
            if($result['id']==46){//易通金服
                $pay = new \pay\Yitianmao();
                $getWay =  $pay->byPay($deposit,$payNo);
                if(isset($getWay['errorcode'])){
                    return array_merge($tdata,['msg'=>$getWay['errormessage']]);
                }else{
                    return array_merge($tdata,['status'=>1],["data"=>["url"=>$getWay,"status"=>1]]);
                }
                return $tdata;
            }

            //天下
            if($result['id']==55){//
                $pay = new \pay\Tixia();
                $getWay =  $pay->byPay($deposit,$payNo,$CertName,$CertNo,$Phone);
                if(!$getWay){
                    return array_merge($tdata,['msg'=>"第三方接口异常"]);
                }else{
                    if(is_array($getWay)){
                        return array_merge($tdata,['status'=>0,"msg"=>$getWay['msg']]);
                    }
                    return array_merge($tdata,['status'=>1],["data"=>["url"=>$getWay,"status"=>1]]);
                }
                return $tdata;

            }

            if($result['id']==57){
                $pay = new \pay\Lian();
                $getWay =  $pay->byPay($deposit,$payNo,$CertName,$CertNo,$Phone);
                if(!$getWay){
                    return array_merge($tdata,['msg'=>"第三方接口异常"]);
                }else{
                    if(is_array($getWay)){
                        return array_merge($tdata,['status'=>0,"msg"=>$getWay['msg']]);
                    }
                    return array_merge($tdata,['status'=>1],["data"=>["url"=>$getWay,"status"=>1]]);
                }
                return $tdata;
            }


    if($result['id']==58){
        $pay = new \pay\Tlian();
        $getWay =  $pay->byPay($deposit,$payNo,$CertName,$CertNo,$Phone);
        if(!$getWay){
            return array_merge($tdata,['msg'=>"第三方接口异常"]);
        }else{
            if(is_array($getWay)){
                return array_merge($tdata,['status'=>0,"msg"=>$getWay['msg']]);
            }
            return array_merge($tdata,['status'=>1],["data"=>["url"=>$getWay,"status"=>1]]);
        }
        return $tdata;
    }


    if($result['id']==59){

        $pay = new \pay\Znan();
        $Bank = new \app\np\model\UsersBank();

        $BankResult = $Bank->where('user_id',$user_id['user_id'])->find();


        if(isset($BankResult['bank_no'])){
                $bank_no = $BankResult['bank_no'];
        }
        $getWay =  $pay->byPay($deposit,$payNo,$CertName,$CertNo,$Phone,isset($bank_no)?$bank_no:"");
        if(!$getWay){
            return array_merge($tdata,['msg'=>"第三方接口异常"]);
        }else{
            if(is_array($getWay)){
                return array_merge($tdata,['status'=>0,"msg"=>$getWay['msg']]);
            }
            return array_merge($tdata,['status'=>1],["data"=>["url"=>$getWay,"status"=>1]]);
        }
        return $tdata;
    }
            return $tdata;
}

function getConfigByZhifu(){
    $ConfigsModel = new \app\admin\model\Configs();
    $result =  $ConfigsModel->where(["group_config_id"=>5,"is_position"=>1])->find();
    return $result;
}

/**
 * @return array|false|PDOStatement|string|\think\Model 短信配置
 */
function getConfigsms(){
    $ConfigsModel = new \app\admin\model\Configs();
    $result =  $ConfigsModel->where(["group_config_id"=>8,"is_position"=>1])->find();
    return $result;
}



function filter_agent2($res,$id,&$arr=[]){
    if(empty($arr)){
        $yes = get_self($res,$id);
        $arr = array_merge($arr,$yes);
    }
    $kds = seach_son($res,$id);
    if(empty($kds)){
        return $arr;
    }
    if(!empty($kds)&&is_array($kds)){
        $arr = array_merge($arr,$kds);
        foreach($kds as $kk=>$vv){
            filter_agent2($res,$vv['id'],$arr);

        }
    }
    return $arr;
}



//过滤代理商
function filter_agent($res,$id,&$arr=[]){
    if(empty($arr)){
        $yes = get_self($res,$id);
        $arr = array_merge($arr,$yes);
    }
    $kds = seach_son($res,$id);
    if(empty($kds)){
        return $arr;
    }
    if(!empty($kds)&&is_array($kds)){
        $arr = array_merge($arr,$kds);
        foreach($kds as $kk=>$vv){
            filter_agent($res,$vv['id'],$arr);
        }
    }
    return $arr;
}

function seach_son($arr,$id){
          $arrs = [];
       foreach($arr as $k=>$v){
                    if($v['agent_id']==$id){

                        $arrs[] = $v;
                    }

       }
       return $arrs;
}

function get_self($arr,$id){
    $arrs = [];
    foreach($arr as $k=>$v){
        if($v['id']==$id){
            $v['agent_id'] = 0;
            $arrs[] = $v;
        }
    }
    return $arrs;
}






//获取代理商的一串
function filter_agent_all($user_id){
    //关于该用户的代理串
     $arr  = [];
    $users =new \app\admin\model\Users;
    $resUsers = $users->where("id",$user_id)->find();
    if(!empty($resUsers)&&isset($resUsers['agent_id'])){
                            $agent_id = $resUsers['agent_id'];//获取当前用户的代理商id和业务员id
                            $staff_id = $resUsers['staff_id'];// 业务员id
                            if(!$agent_id){
                                    return [];
                            }
       $arr =   trs_agent($agent_id,$staff_id);

    }
    if(!empty($arr)){
        $arr = array_reverse($arr);
    }
    return $arr;
}




function trs_agent($agent_id,$staff_id=0){
                static $arr =[];
                static $AdminAgent;
                static $AdminStaff;
                if(!$staff_id){
                    $staff_id = 0;
                }
      $AdminAgent = new \app\admin\model\AdminAgent;
      $AdminStaff = new \app\admin\model\AdminStaff;


                $where = [];
    $res = $AdminAgent->where("id",$agent_id)->find();

    if(isset($res['id'])&&!empty($res['id'])){
                $d = [];
                $d['id'] = $agent_id;
                 if(!empty($staff_id)){
                        //业务员佣金
                   $dks =   $staffs = $AdminStaff->field("*,commison as ccom")->where("id",$staff_id)->find();
                     $d['staff_commission'] = !empty($dks['ccom'])?$dks['ccom']:0;
                 }else{
                     $d['staff_commission']  = 0;
                 }
                $d['staff_id'] = $staff_id;
                $d['agent_id'] = $res['agent_id'];
                $d['commission'] = !empty($res['commission'])?$res['commission']:0;
                array_push($arr,$d);
        trs_agent($d['agent_id'] ,0);


    }else{
                return $arr;
    }
    return $arr;

}





function getpowers(){
    $Cstatic= controller('base/Cstatic');
   return  $Cstatic->get('power');

}


function tree($agent_id){
    $where = [];
    $model = new \app\admin\model\AdminAgent;
    $res =    $model->field("id,agent_id,agent_no")->where($where)->select();
    if(!empty($res)){
        foreach($res as $k=>&$v){
            $v = $v->toArray();
        }
    }else{
        return  [];
    }
    //    echo(json_encode($res));exit;
    if(isset($agent_id)){
        $arr = [];
        $res = filter_agent2($res,$agent_id,$arr);
    }else{
        return   [];
    }
    if(empty($res)){
        return [];
    }

    $r = \tool\Trees::makeTreeForHtml($res);
    return   $r;
}

//代理商可处理的
function dailiwith($agents_id,$agents_ids=""){
                    if($agents_ids=="all"){
                        return true;
                    }else{
                            if(is_array($agents_ids)){
                                    if(in_array($agents_id,$agents_ids)){
                                                return true;
                                    }
                            }
                    }
                    return false;
}


//获取角色拥有的权限
function getPower($id){
    $model = new \app\admin\model\Role;
    $modelPrivilege = new \app\admin\model\Privilege;
    $Cstatic= controller('base/Cstatic');

    $res = $model->where("id",$id)->find();

    $data = [];
  if(empty($res)){
        $data['privilege'] = "";
        $data['layer_privilege'] = "";
        return $data;
    }

   $res = $res->toArray();
    if(!empty($res)) {
        if ($res['privilege'] != "all")
        {

            //获取控制层的权限
            //搜索当前的控制权限数组
            $privilege = explode(",", $res['privilege']);

            if (!empty($privilege)) {
                $privilege = array_unique(array_filter($privilege,function ($val) {
                    return is_numeric($val);
                }));
                if(!empty($privilege)){
                    $privilege = implode(",", $privilege);
                    $privilegelist = $modelPrivilege->where("id in({$privilege})")->where("is_power",1)->select();
                    $Cstatic->set("privilege", $privilegelist);
                    $data['privilege'] = $privilegelist;
                }

            }
        } else {
            $Cstatic->set("privilege", "all");
            $data['privilege'] = "all";

        }

        if ($res['layer_privilege'] != "all") {
            //获取显示控制层的权限
            $layer_privilege = explode(",", $res['layer_privilege']);
            if (!empty($layer_privilege)) {
                $layer_privilege = array_unique(array_filter($layer_privilege,function ($val) {
                    return is_numeric($val);
                }));
                if(!empty($layer_privilege)){
                    $layer_privilege = implode(",", $layer_privilege);
                    $layer_privilegeList = $modelPrivilege->where("id in({$layer_privilege}) ")->where("is_nav",1)->select();
                    $Cstatic->set("layer_privilege", $layer_privilegeList);
                    $data['layer_privilege'] =$layer_privilegeList;
                }
            }

        } else {
            $Cstatic->set("layer_privilege", "all");
            $data['layer_privilege'] ="all";

        }
        //if($res)
    }

    return $data;
}

/**
 * @param $result
 * @param bool $isKeys  是否是主表Kyes
 * @param int $isHasAgent
 * @return mixed
 */
function trs_resut($result,$isKeys=false,$isHasAgent=false){

    $rows = Cache::get(w_g("sid"));

    $agents_ids = w_g("agents_ids");//ID列表
    //超级管理员的操作
    if($isHasAgent){
        $result->join("admin_agent ag","ag.id=a.agent_id","left");
    }

    if($rows['admin_group_id']==1){
        return $result;
    }

    if(w_g("no_in")){
        return $result;
    }

    //主键操作 U

    if($isKeys){
        $result->where('a.agent_id',"in",$agents_ids);
    }else{
        $result->where('u.agent_id',"in",$agents_ids);

    }

    return $result;
}










function mbstringToArray($str,$charset) {
    $strlen=mb_strlen($str);
    while($strlen){
        $array[]=mb_substr($str,0,1,$charset);
        $str=mb_substr($str,1,$strlen,$charset);
        $strlen=mb_strlen($str);
    }
    return $array;
}






function saveBase64Image($base64_image_content){

    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){

        //图片后缀
        $type = $result[2];

        //保存位置--图片名
        $image_name=date('His').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT).".".$type;
        $image_url = '/uploads/image/'.date('Ymd').'/'.$image_name;
        if(!is_dir(dirname('.'.$image_url))){
            mkdir(dirname('.'.$image_url),0777,true);
            chmod(dirname('.'.$image_url), 0777);
//            umask($oldumask);

        }

        //解码
        $decode=base64_decode(str_replace($result[1], '', $base64_image_content));
        if (file_put_contents('.'.$image_url, $decode)){
            $data['code']=1;
            $data['imageName']=$image_name;
            $data['url']=$image_url;
            $data['msg']='保存成功！';
        }else{
            $data['code']=0;
            $data['imgageName']='';
            $data['url']='';
            $data['msg']='图片保存失败！';
        }
    }else{
        $data['code']=1;
        $data['imgageName']='';
        $data['url']='';
        $data['msg']='base64图片格式有误！';


    }
    return $data;


}



//过滤post来的数据
function delwithData($self){
    $keys = $self->scan_name; //用户信息修改
    $data = [];
    if(!empty($keys)){
        foreach($keys as $k=>$v){
            if(isset($self->$v)){
                $data[$v] = $self->$v;
            }
        }
    }
    w_s("scan_nameData",$data);

    return $data;
}

/**
 * @return array 股票指数详情
 */
function zhiShu(){
   $url = "http://q.jrjimg.cn/?q=cn|i&i=399005,000001,399001,399006&c=l&n=hqa_quote";
    return getJRData($url,"var hqa_quote=");
}


/**
 *  概念板块
 */
function bangKuai(){
    $url = "http://q.jrjimg.cn/?q=cn|bk|5&n=hqa&c=l&o=pl,d&p=1010&_dc=1515388071945";
    return getJRData($url);
}

/**
 *  行業板块
 */
function bangHangyeKuai(){
    $url = "http://q.jrjimg.cn/?q=cn|bk|17&n=hqa&c=l&o=pl,d&p=1010&_dc=1515388123727";
    return getJRData($url);
}


function getJRData($url,$base="var hqa="){
    $f_data = [
        "status"=>0,
        "msg"=>"异常",
        "data"=>[],
    ];

    $http = new \http\Http();
    $result = $http->get($url);
    $result = mb_convert_encoding($result,"UTF-8","GBK");
    $result= str_replace($base," ",$result);
    if(preg_match('/\w:/', $result)){
        $result = preg_replace('/(\w+):/is', '"$1":', $result);
        $result= str_replace(";"," ",$result);
        $result = json_decode($result,true);
        if(isset($result['HqData'])){
            $HqData = $result['HqData'];
            return array_merge($f_data,['status'=>1,"msg"=>"查询成功","data"=>$HqData]);
        }
    }
    return array_merge($f_data,['msg'=>"暂无数据"]);
}

//获取排行榜数据
function getBang($bang="top"){
    $f_data = [
        "status"=>0,
        "msg"=>"异常",
    ];
    if($bang=="top"){
        $url ="http://q.jrjimg.cn/?q=cn|s|sa&n=hqa&o=pl,d&p=1010";
    }else{
        $url ="http://q.jrjimg.cn/?q=cn|s|sa&n=hqa&o=pl,a&p=1010";
    }

    return getJRData($url);
}


//设置全局变量
function w_s($key,$val){
    \app\base\controller\Cstatic::instance()->set($key,$val);
}
//获取全局变量
function w_g($key){
    $instance = \app\base\controller\Cstatic::instance();
    if($instance->has($key)){
        return $instance->get($key);
    }
    return false;
}


/**
 * @param $keys
 * @param $attr
 * @return string 给数组添加默认key
 */
function keyaddTable($keys,$attr){
    $keys = array_keys($keys);
    if(!empty($keys)){
        $keys = array_map(function($val)use($attr){
            return $attr.".".$val;
        },$keys);
        return implode(",",$keys);
    }
    return "";

}

/**
 * @param $keys
 * @param $attr
 * @return string 给数组添加默认key
 */
function keysAddFiles($keys,$attr){

    if(!empty($keys)){
        $keys = array_map(function($val)use($attr){
            return $attr.".".$val;
        },$keys);
        return implode(",",$keys);
    }
    return "";

}

/**
 * @return string 获取基础系统配置
 */
function getOS(){

 return PHP_OS;
}


/**
 *
 *  获取不重复的编号
 */
function getOnlySn($model,$key){
    $i=1;
    /**
     *  代理编号的重复
     */
    $sn = ordersn();
    $where[$key] = $sn;
    while($i){
        $countagent_count = $model->baseCount($where);
        if($countagent_count>0){
          $sn = ordersn();
        }else{
            $i=0;
        }
    }
    return $sn;
}

/**
 *  获取当前代理商的角色
 */
function getAuth($sidRow){
    $RolefModel = new \app\admin\model\Role();
    $agent_id = $sidRow['agent_id'];

    if(w_g('agents_ids')=='all'){
        if(empty($agent_id)){
            $agent_id = 0;
        }
    }


    $AdminStaffResult =  $RolefModel->field("role_name,id")->where("agent_id",$agent_id)->select();
    if(getOS()=="Linux"){
        $sql = $RolefModel->getLastSql();
        error_log($sql.PHP_EOL, 3, "/home/wwwlogs/sql.log");

    }
    if(!empty($AdminStaffResult)){
        $AdminStaffResult = json_decode(json_encode($AdminStaffResult),true);
        return $AdminStaffResult;
    }
    return [];


}


/**
 *  获取当前代理商的角色
 */
/*function getAuth($sidRow,$agents_ids){
    $roleModel = new \app\admin\model\Role();
    $AdminAgentModel = new \app\admin\model\AdminAgent();
    $PowerList = $roleModel->field("id,role_name")->select();

    if(!empty($PowerList)){
        $PowerList = json_decode(json_encode($PowerList),true);


        w_s("PowerList",$PowerList);

        $PowerList = array_column($PowerList,"id");
    }

    if($agents_ids=="all"){
        return $PowerList;
    }

    $agent_id = $sidRow['agent_id'];
    if(!$agent_id){
        return [];
    }



    $AdminAgentResult = $AdminAgentModel->where(['id'=>$agent_id])->find();

    return !empty($AdminAgentResult['auth'])?$AdminAgentResult["auth"]:[];

}*/

/**
 * @param $func
 * @return array 函数方法反射
 */
function getFucntionParameterName($func) {
    $ReflectionFunc = new \ReflectionFunction($func);
    $depend = array();
    foreach ($ReflectionFunc->getParameters() as $value) {
        $depend[] = $value->name;
    }
    return $depend;
}

function CalcManger($manage_per){
    return   bcdiv($manage_per,100,5);
}


/**
 * 签名字符串
 * @param $prestr 需要签名的字符串
 * @param $key 私钥
 * return 签名结果
 */
function md5Sign($prestr, $key) {

    $prestr = $prestr ."&key=". $key;
    if(getOS()=="Linux"){
        error_log($prestr.PHP_EOL, 3, "/home/wwwlogs/lianlian_yuanchuang_apikey.log");

    }
    //file_put_contents("log.txt","签名原串:".$logstr."\n", FILE_APPEND);
    return md5($prestr);
}

/**
 * 验证签名
 * @param $prestr 需要签名的字符串
 * @param $sign 签名结果
 * @param $key 私钥
 * return 签名结果
 */
function md5Verify($prestr, $sign, $key) {

    $prestr = $prestr ."&key=". $key;
    //file_put_contents("log.txt","prestr:".$logstr."\n", FILE_APPEND);
    $mysgin = md5($prestr);
    //file_put_contents("log.txt","1:".$mysgin."\n", FILE_APPEND);
    if($mysgin == $sign) {
        return true;
    }
    else {
        return false;
    }
}




/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
function createLinkstring($para) {
    $arg  = "";
    while (list ($key, $val) = each ($para)) {
        $arg.=$key."=".$val."&";
    }
    //去掉最后一个&字符
    $arg = substr($arg,0,count($arg)-2);
    //file_put_contents("log.txt","转义前:".$arg."\n", FILE_APPEND);
    //如果存在转义字符，那么去掉转义
    if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
    //file_put_contents("log.txt","转义后:".$arg."\n", FILE_APPEND);
    return $arg;
}
/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串，并对字符串做urlencode编码
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
function createLinkstringUrlencode($para) {
    $arg  = "";
    while (list ($key, $val) = each ($para)) {
        $arg.=$key."=".urlencode($val)."&";
    }
    //去掉最后一个&字符
    $arg = substr($arg,0,count($arg)-2);

    //如果存在转义字符，那么去掉转义
    if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}

    return $arg;
}
/**
 * 除去数组中的空值和签名参数
 * @param $para 签名参数组
 * return 去掉空值与签名参数后的新签名参数组
 */
function paraFilter($para) {
    $para_filter = array();
    while (list ($key, $val) = each ($para)) {
        if($key == "sign" || $val == "")continue;
        else	$para_filter[$key] = $para[$key];
    }
    return $para_filter;
}
/**
 * 对数组排序
 * @param $para 排序前的数组
 * return 排序后的数组
 */
function argSort($para) {
    ksort($para);
    reset($para);
    return $para;
}
/**
 * 写日志，方便测试（看网站需求，也可以改成把记录存入数据库）
 * 注意：服务器需要开通fopen配置
 * @param $word 要写入日志里的文本内容 默认值：空值
 */
function logResult($word='') {
    $fp = fopen("log.txt","a");
    flock($fp, LOCK_EX) ;
    fwrite($fp,"执行日期：".strftime("%Y%m%d%H%M%S",time())."\n".$word."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

/**
 * 远程获取数据，POST模式
 * 注意：
 * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
 * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
 * @param $url 指定URL完整路径地址
 * @param $cacert_url 指定当前工作目录绝对路径
 * @param $para 请求的数据
 * @param $input_charset 编码格式。默认值：空值
 * return 远程输出的数据
 */
function getHttpResponsePOST($url, $cacert_url, $para, $input_charset = '') {

    if (trim($input_charset) != '') {
        $url = $url."_input_charset=".$input_charset;
    }
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
    curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);//证书地址
    curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
    curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
    curl_setopt($curl,CURLOPT_POST,true); // post传输数据
    curl_setopt($curl,CURLOPT_POSTFIELDS,$para);// post传输数据
    $responseText = curl_exec($curl);
    //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
    curl_close($curl);

    return $responseText;
}

/**
 * 远程获取数据，GET模式
 * 注意：
 * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
 * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
 * @param $url 指定URL完整路径地址
 * @param $cacert_url 指定当前工作目录绝对路径
 * return 远程输出的数据
 */
function getHttpResponseGET($url,$cacert_url) {
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
    curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
    curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);//证书地址
    $responseText = curl_exec($curl);
    //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
    curl_close($curl);

    return $responseText;
}

/**
 * 实现多种字符编码方式
 * @param $input 需要编码的字符串
 * @param $_output_charset 输出的编码格式
 * @param $_input_charset 输入的编码格式
 * return 编码后的字符串
 */
function charsetEncode($input,$_output_charset ,$_input_charset) {
    $output = "";
    if(!isset($_output_charset) )$_output_charset  = $_input_charset;
    if($_input_charset == $_output_charset || $input ==null ) {
        $output = $input;
    } elseif (function_exists("mb_convert_encoding")) {
        $output = mb_convert_encoding($input,$_output_charset,$_input_charset);
    } elseif(function_exists("iconv")) {
        $output = iconv($_input_charset,$_output_charset,$input);
    } else die("sorry, you have no libs support for charset change.");
    return $output;
}
/**
 * 实现多种字符解码方式
 * @param $input 需要解码的字符串
 * @param $_output_charset 输出的解码格式
 * @param $_input_charset 输入的解码格式
 * return 解码后的字符串
 */
function charsetDecode($input,$_input_charset ,$_output_charset) {
    $output = "";
    if(!isset($_input_charset) )$_input_charset  = $_input_charset ;
    if($_input_charset == $_output_charset || $input ==null ) {
        $output = $input;
    } elseif (function_exists("mb_convert_encoding")) {
        $output = mb_convert_encoding($input,$_output_charset,$_input_charset);
    } elseif(function_exists("iconv")) {
        $output = iconv($_input_charset,$_output_charset,$input);
    } else die("sorry, you have no libs support for charset changes.");
    return $output;
}

//格式化时间戳
function local_date($format, $time = NULL)
{
    if ($time === NULL)
    {
        $time = gmtime();
    }
    elseif ($time <= 0)
    {
        return '';
    }
    return date($format, $time);
}


function getJsonVal($json, $k){
    if(isset($json->{$k})){
        return trim($json->{$k});
    }
    return "";
}




function Rsasign($data,$priKey) {

    //转换为openssl密钥，必须是没有经过pkcs8转换的私钥
    $res = openssl_get_privatekey($priKey);

    //调用openssl内置签名方法，生成签名$sign
    openssl_sign($data, $sign, $res,OPENSSL_ALGO_MD5);

    //释放资源
    openssl_free_key($res);

    //base64编码
    $sign = base64_encode($sign);
    //file_put_contents("log.txt","签名原串:".$data."\n", FILE_APPEND);
    return $sign;
}

/********************************************************************************/

/**RSA验签
 * $data待签名数据(需要先排序，然后拼接)
 * $sign需要验签的签名,需要base64_decode解码
 * 验签用连连支付公钥
 * return 验签是否通过 bool值
 */
function Rsaverify($data, $sign,$llpay_public_key="")  {
    //读取连连支付公钥文件
    $pubKey = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCSS/DiwdCf/aZsxxcacDnooGph3d2JOj5GXWi+q3gznZauZjkNP8SKl3J2liP0O6rU/Y/29+IUe+GTMhMOFJuZm1htAtKiu5ekW0GlBMWxf4FPkYlQkPE0FtaoMP3gYfh+OwI+fIRrpW3ySn3mScnc6Z700nU/VYrRkfcSCbSnRwIDAQAB
-----END PUBLIC KEY-----
';

    //转换为openssl格式密钥
    $res = openssl_get_publickey($pubKey);

    //调用openssl内置方法验签，返回bool值
    $result = (bool)openssl_verify($data, base64_decode($sign), $res,OPENSSL_ALGO_MD5);

    //释放资源
    openssl_free_key($res);

    //返回资源是否成功
    return $result;
}

